﻿using System;
using System.IO;
using NUnit.Framework;
using Smartkernel.IO;

namespace Smartkernel.NUnitTest.IO
{
    [Category("IO")]
    [TestFixture]
    public class SmartFileSystemWatcherTest
    {
        [Test]
        public void Test()
        {
            //【01】添加监视文件的测试（涉及方法：Add）
            bool isChange1 = false;
            bool isChange2 = false;
            Console.WriteLine("[01]测试是否检测到文件变化");
            string path1 = Environment.CurrentDirectory + @"\SmartFileSystemWatcher_NUnitTest1.txt";
            string path2 = Environment.CurrentDirectory + @"\SmartFileSystemWatcher_NUnitTest2.txt";
            File.CreateText(path1).Dispose();
            SmartFileSystemWatcher.Add(path1, delegate { isChange1 = true; });
            SmartFileSystemWatcher.Add(path2, delegate { isChange2 = true; });
            using (StreamWriter streamWriter = new StreamWriter(path1, true))
            {
                streamWriter.Write(DateTime.Now.Ticks);
            }
            using (StreamWriter streamWriter = new StreamWriter(path2, true))
            {
                streamWriter.Write(DateTime.Now.Ticks);
            }
            System.Threading.Thread.Sleep(1000);
            Assert.AreEqual(isChange1, true);
            Assert.AreEqual(isChange2, true);

            //【02】删除监视文件的测试（涉及方法：Remove）
            SmartFileSystemWatcher.Remove(path1);
            isChange1 = false;
            isChange2 = false;
            using (StreamWriter streamWriter = new StreamWriter(path1, true))
            {
                streamWriter.Write(DateTime.Now.Ticks);
            }
            using (StreamWriter streamWriter = new StreamWriter(path2, true))
            {
                streamWriter.Write(DateTime.Now.Ticks);
            }
            System.Threading.Thread.Sleep(1000);
            Assert.AreEqual(isChange1, false);
            Assert.AreEqual(isChange2, true);

            //【03】清除全部监视文件的测试（涉及方法：Clear）
            isChange1 = false;
            isChange2 = false;
            SmartFileSystemWatcher.Clear();
            using (StreamWriter streamWriter = new StreamWriter(path1, true))
            {
                streamWriter.Write(DateTime.Now.Ticks);
            }
            using (StreamWriter streamWriter = new StreamWriter(path2, true))
            {
                streamWriter.Write(DateTime.Now.Ticks);
            }
            System.Threading.Thread.Sleep(1000);
            Assert.AreEqual(isChange1, false);
            Assert.AreEqual(isChange2, false);
            File.Delete(path1);
            File.Delete(path2);
        }
    }
}
